// 表单生成器
import formFieldsType from '@/utils/formFieldsType';
import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  CopyOutlined,
  DeleteOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { Input, InputNumber, Space, Switch, Tooltip } from 'antd';
import styles from './index.less';

import guid from '@/utils/guid';
import { useEffect, useState } from 'react';
import FormItem from './components/FormItem';

interface Props {
  defaultValue: GeneratorModel.FormItem[];
  onChange: (value: GeneratorModel.FormItem[]) => void;
}
export default function MyGenerator(props: Props) {
  const { defaultValue, onChange } = props;
  const [schema, setSchema] = useState<GeneratorModel.FormItem[]>([]);
  const [active, setActive] = useState<number>(0);
  const [activeFormItem, setActiveFormItem] = useState<GeneratorModel.FormItem>({
    fieldName: '',
    name: '',
    type: 1,
  });
  useEffect(() => {
    setSchema(defaultValue);
    onChange(defaultValue);
    // if (defaultValue.length > 0) {
    //   setActiveFormItem(defaultValue[0]);
    // }
  }, []);

  useEffect(() => {
    if (schema.length > 0) {
      setActiveFormItem(schema[active]);
    }
  }, [active]);

  const changePulbic = (e: any) => {
    // console.log(e);
    const value = e.target.value;

    const key = e.target.dataset.key;

    console.log(key);

    activeFormItem[key] = value;

    setActiveFormItem({ ...activeFormItem });
    schema[active] = activeFormItem;
    setSchema(schema);
    onChange(schema);
  };

  const changeSwitch = (checked: boolean) => {
    const value = checked;
    activeFormItem.isNull = value ? 1 : 0;

    setActiveFormItem({ ...activeFormItem });
    schema[active] = activeFormItem;
    setSchema(schema);
    onChange(schema);
  };

  const changeMaxLength = (value: number | string | null) => {
    activeFormItem.maxLength = Number(value);

    setActiveFormItem({ ...activeFormItem });
    schema[active] = activeFormItem;
    setSchema(schema);
    onChange(schema);
  };

  const leftHtmlShowItem = (data: any) => {
    return data.map((item: any) => {
      return (
        <div
          key={item.id}
          className={styles.itemInput}
          onClick={() => {
            console.log(item);
            //添加组件
            const formitem = {
              fieldName: guid(10),
              name: item.value,
              type: item.id,
              remark: '',
              inputTips: '',
              maxLength: 0,
              defaultValue: '',
              isNull: 0, //是否必填 1 是 0 否
              sorting: 0, //排序 从小到大
              options: '', //如果类型是选项，此处不能为空，多个选项以，隔开
              dataSource: '', //数据源
            };
            schema.push(formitem);

            setSchema([...schema]);
            onChange(schema);
            setActive(schema.length - 1);
            setActiveFormItem(formitem);
          }}
        >
          <span>{item.value}</span>
        </div>
      );
    });
  };

  const leftHtmlShow = () => {
    return formFieldsType.map((item: any) => {
      return (
        <div key={item.label} className={styles.item}>
          <div className={styles.label}>{item.label}</div>
          <div className={styles.data}>{leftHtmlShowItem(item.data)}</div>
        </div>
      );
    });
  };

  return (
    <div className={styles.mycard}>
      <div className={styles.left}>{leftHtmlShow()}</div>
      <div className={styles.center}>
        {schema.map((item, index) => {
          return (
            <div
              key={index}
              onClick={() => {
                setActive(index);
              }}
              className={`${styles.module} ${active === index ? styles.active : ''}`}
            >
              <FormItem item={item} />
              {active === index ? (
                <div className={styles.delete}>
                  <Space style={{ cursor: 'pointer' }}>
                    <ArrowUpOutlined
                      onClick={() => {
                        if (index === 0) {
                          return;
                        }
                        const list = JSON.parse(JSON.stringify(schema));
                        list.splice(index - 1, 1, ...list.splice(index, 1, list[index - 1]));
                        setActive(index - 1);
                        setActiveFormItem({ ...schema[index - 1] });

                        setSchema([...list]);
                        onChange(schema);
                      }}
                      style={{ fontSize: 12 }}
                    />
                    <ArrowDownOutlined
                      onClick={() => {
                        if (index === schema.length - 1) {
                          return;
                        }
                        const list = JSON.parse(JSON.stringify(schema));
                        list.splice(index + 1, 1, ...list.splice(index, 1, list[index + 1]));
                        setActive(index + 1);
                        setActiveFormItem({ ...schema[index + 1] });

                        setSchema([...list]);
                        onChange(schema);
                      }}
                      style={{ fontSize: 12 }}
                    />
                    <CopyOutlined
                      onClick={() => {
                        const list = JSON.parse(JSON.stringify(schema));
                        const itemModel = list[index];
                        itemModel.fieldName = guid(10);
                        schema.push(itemModel);

                        setActiveFormItem({ ...itemModel });

                        setSchema([...schema]);
                        onChange(schema);
                        setActive(schema.length - 1);
                      }}
                      style={{ fontSize: 12 }}
                    />
                    <DeleteOutlined
                      onClick={() => {
                        schema.splice(index, 1);
                        setSchema([...schema]);
                        onChange(schema);
                        setActive(index);
                        setActiveFormItem({ ...schema[index] });
                      }}
                      style={{ fontSize: 12 }}
                    />
                  </Space>
                </div>
              ) : (
                ''
              )}
            </div>
          );
        })}
      </div>
      <div className={styles.right}>
        <div className={styles.label}>组件属性</div>
        <div className={styles.data}>
          <div className={styles.item}>
            <div className={styles.labelText}>字段ID</div>
            <div className={styles.value}>
              <Input
                placeholder="请输入字段ID"
                value={activeFormItem.fieldName}
                data-key="fieldName"
                onChange={changePulbic}
              />
            </div>
          </div>
          <div className={styles.item}>
            <div className={styles.labelText}>字段名称</div>
            <div className={styles.value}>
              <Input
                placeholder="请输入字段名称"
                value={activeFormItem.name}
                data-key="name"
                onChange={changePulbic}
              />
            </div>
          </div>
          <div className={styles.item}>
            <div className={styles.labelText}>字段说明</div>
            <div className={styles.value}>
              <Input
                placeholder="请输入字段说明"
                value={activeFormItem.remark}
                data-key="remark"
                onChange={changePulbic}
              />
            </div>
          </div>
          <div className={styles.item}>
            <div className={styles.labelText}>输入提示</div>
            <div className={styles.value}>
              <Input
                placeholder="请输入输入提示"
                value={activeFormItem.inputTips}
                data-key="inputTips"
                onChange={changePulbic}
              />
            </div>
          </div>
          {activeFormItem.type === 1 || activeFormItem.type === 3 ? (
            <div className={styles.item}>
              <div className={styles.labelText}>最大长度</div>
              <div className={styles.value}>
                <InputNumber
                  placeholder="请输入最大长度"
                  value={activeFormItem.maxLength}
                  onChange={changeMaxLength}
                />
              </div>
            </div>
          ) : (
            ''
          )}

          <div className={styles.item}>
            <div className={styles.labelText}>是否必填</div>
            <div className={styles.value}>
              <Switch
                checkedChildren="是"
                unCheckedChildren="否"
                checked={activeFormItem.isNull === 1}
                onChange={changeSwitch}
              />
            </div>
          </div>
          {activeFormItem.type === 5 ? (
            <div className={styles.item}>
              <div className={styles.labelText}>
                <Space>
                  <span>下拉数据</span>
                  <Tooltip placement="top" title={'数据之间需逗号隔开'}>
                    <QuestionCircleOutlined style={{ color: '#909399' }} />
                  </Tooltip>
                </Space>
              </div>

              <div className={styles.value}>
                <Input
                  placeholder="请输入下拉数据"
                  value={activeFormItem.options}
                  data-key="options"
                  onChange={changePulbic}
                />
              </div>
            </div>
          ) : (
            ''
          )}

          {activeFormItem.type === 12 || activeFormItem.type === 13 ? (
            <div className={styles.item}>
              <div className={styles.labelText}>
                <Space>
                  <span>下拉数据源</span>
                  <Tooltip
                    placement="top"
                    title={
                      activeFormItem.type === 12
                        ? "数据源返回需为[{ value: 'jack', label: 'Jack' }]结构"
                        : "数据源返回需为[{ value: 'jack', label: 'Jack',children:[] }]结构"
                    }
                  >
                    <QuestionCircleOutlined style={{ color: '#909399' }} />
                  </Tooltip>
                </Space>
              </div>
              <div className={styles.value}>
                <Input
                  placeholder="请输入下拉数据源接口"
                  value={activeFormItem.dataSource}
                  data-key="dataSource"
                  onChange={changePulbic}
                />
              </div>
            </div>
          ) : (
            ''
          )}
        </div>
      </div>
    </div>
  );
}
